package com.bw.packcar.utils

import android.animation.Animator
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.util.Log
import android.view.*
import android.view.animation.AnticipateInterpolator
import android.view.animation.LinearInterpolator
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.bw.packcar.databinding.PopStringBinding

/**
 * Author : 兰宏宇
 * Created by lhy on 2025/5/12.
 * Description: 弹窗工具类
 */
class PopUtils(context: Context, private val anchorView: View) : PopupWindow(context) {
    val binding by lazy { PopStringBinding.inflate(LayoutInflater.from(context)) }

    private val entryAnimator = ObjectAnimator.ofFloat(binding.llBox, "translationY", 0f, 0f)
        .apply {
            duration = 300
            interpolator = LinearInterpolator()
        }

    private val exitAnimator = ObjectAnimator.ofFloat(binding.llBox, "translationY", 0f, 0f)
        .apply {
            duration = 300
            interpolator = LinearInterpolator()
        }




    init {

        contentView = binding.root
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        isFocusable = true
        setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))



        anchorView.viewTreeObserver.addOnGlobalLayoutListener(
            object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    // 移除监听避免重复触发
                    anchorView.viewTreeObserver.removeOnGlobalLayoutListener(this)
                    width = anchorView.measuredWidth

                }
            }
        )

        // 确保在视图布局完成后获取高度
        binding.llBox.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                binding.llBox.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val height = binding.llBox.measuredHeight
                entryAnimator.setFloatValues(-height.toFloat(), 0f)
                exitAnimator.setFloatValues(0f, -height.toFloat())
            }
        })


    }

    // 显示方法优化
    fun show() {
        showAsDropDown(anchorView, 0, 0, Gravity.START)
        entryAnimator.start()
    }

    override fun dismiss() {
        entryAnimator.cancel()
        exitAnimator.start()


        exitAnimator.addListener(object :Animator.AnimatorListener{
            override fun onAnimationStart(animation: Animator) {
            }

            override fun onAnimationEnd(animation: Animator) {
                exitAnimator.cancel()

                super@PopUtils.dismiss()

            }

            override fun onAnimationCancel(animation: Animator) {
            }

            override fun onAnimationRepeat(animation: Animator) {
            }

        })

    }




}